package com.aabte.permissionframeworklearn.permission.common;

import com.aabte.permissionframeworklearn.permission.exception.ParamException;
import com.aabte.permissionframeworklearn.permission.exception.PermissionException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Daniel
 */
@Slf4j
public class SpringExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(
            HttpServletRequest request, HttpServletResponse response,
            Object handler, Exception ex) {

        String url = request.getRequestURL().toString();

        ModelAndView mv;
        String defaultMsg = "System error!";

        if (url.endsWith(".json")) {
            if (ex instanceof PermissionException
                    | ex instanceof ParamException) {
                ResponseBean responseBean = ResponseBean.fail(ex.getMessage());
                mv = new ModelAndView("jsonView", responseBean.toMap());
            } else {
                log.error("unknown exception, url: {}", url, ex);
                ResponseBean responseBean = ResponseBean.fail(defaultMsg);
                mv = new ModelAndView("jsonView", responseBean.toMap());
            }
        } else if (url.endsWith(".page")) {
            log.error("unknown page exception, url: {}", url, ex);
            ResponseBean responseBean = ResponseBean.fail(defaultMsg);
            mv = new ModelAndView("exception", responseBean.toMap());
        } else {
            log.error("unknown exception, url: {}", url, ex);
            ResponseBean responseBean = ResponseBean.fail(defaultMsg);
            mv = new ModelAndView("jsonView", responseBean.toMap());
        }

        return mv;
    }
}
